package node_login

import (
	"fmt"
	codecs "sanguo/codec/cs"
	"sanguo/cs"
	cs_message "sanguo/protocol/cs/message"
	"strconv"
	"strings"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/sniperHW/kendynet"
)

var areaID_ int
var loginAddr string

func Start(externalAddr string, areaID string) error {
	loginAddr = externalAddr
	areaID_, _ = strconv.Atoi(areaID)
	reportStatus()

	t := strings.Split(externalAddr, ":")
	port, _ := strconv.Atoi(t[1])
	return cs.StartTcpServer("tcp", fmt.Sprintf("0.0.0.0:%d", port), &gDispatcher)

	//return cs.StartTcpServer("tcp", externalAddr, &gDispatcher)
}

func init() {
	gDispatcher.handlers = map[string]handler{}
	gDispatcher.Register(&cs_message.LoginToS{}, func(session kendynet.StreamSession, msg *codecs.Message) {
		var LoginTime int64
		if LoginTime == 0 {
			LoginTime = time.Now().UnixNano() / 1e6
		}

		login := msg.GetData().(*cs_message.LoginToS)
		Infoln(login.GetUserID(), "OnLogin")
		seq := msg.GetSeriNo()
		GetGame(login.GetUserID(), func(err error, game string, token string) {
			loginResp := &cs_message.LoginToC{}
			if nil == err {
				loginResp.Code = cs_message.EnumType(cs_message.EnumType_OK).Enum()
				loginResp.Game = proto.String(game)
				loginResp.Token = proto.String(token)
			} else {
				Infof(err.Error())
				loginResp.Code = cs_message.EnumType(cs_message.EnumType_ERROR).Enum()
			}

			if LoginTime != 0 {
				useTime := time.Now().UnixNano()/1e6 - LoginTime
				if useTime > 100 {
					Debugln("LoginTime ---------->", useTime)
				}
				LoginTime = 0
			}
			session.Send(codecs.NewMessage(seq, loginResp))

			session.Close("", 1)

		})
	})

}
